<template>
  <div class="image-upload" :style="containerStyle">
    <!-- 图片预览区域 -->
    <div class="image-list">
      <div v-for="(url, index) in imageList" :key="index" class="image-item">
        <img :src="url" :style="imageStyle" @error="handleImageError(index)" />
        <div class="image-actions">
          <n-button circle size="tiny" type="error" @click="handleRemove(index)">
            <template #icon>
              <n-icon><close-outlined /></n-icon>
            </template>
          </n-button>
        </div>
      </div>
      
      <!-- 上传按钮 -->
      <div v-if="imageList.length < maxCount" class="upload-trigger" @click="triggerUpload">
        <n-icon :size="iconSize">
          <cloud-upload-outlined />
        </n-icon>
        <div v-if="!compact" class="upload-text">点击上传</div>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInput"
      type="file"
      :accept="accept"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { NIcon, NButton, useMessage } from 'naive-ui'
import { CloudUploadOutlined, CloseOutlined } from '@vicons/antd'
import request from '@/utils/request'

const message = useMessage()
const fileInput = ref(null)

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: 'image/jpeg,image/png,image/gif'
  },
  size: {
    type: Number,
    default: 100
  },
  compact: {
    type: Boolean,
    default: false
  },
  maxCount: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 图片列表
const imageList = ref([])

// 初始化图片列表
const initImageList = () => {
  if (props.modelValue) {
    imageList.value = props.modelValue.split(';').filter(url => url.trim())
  }
}

// 当组件挂载时，检查初始值
onMounted(() => {
  console.log('初始图片URL:', props.modelValue)
  initImageList()
})

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  console.log('图片URL已更新:', newValue)
  initImageList()
})

// 计算容器样式
const containerStyle = computed(() => ({
  '--upload-size': `${props.size}px`
}))

// 计算图片样式
const imageStyle = computed(() => ({
  width: `${props.size}px`,
  height: `${props.size}px`,
  objectFit: 'cover'
}))

// 计算图标大小
const iconSize = computed(() => props.compact ? props.size / 3 : 20)

// 触发文件选择
const triggerUpload = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileChange = async (e) => {
  const files = Array.from(e.target.files)
  if (files.length === 0) return

  // 检查文件数量限制
  if (imageList.value.length + files.length > props.maxCount) {
    message.error(`最多只能上传${props.maxCount}张图片`)
    return
  }

  // 清空文件输入框，以便可以重复选择同一文件
  e.target.value = ''

  // 上传文件
  for (const file of files) {
    try {
      const formData = new FormData()
      formData.append('file', file) 
      const res = await request.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      // 检查响应格式并正确提取URL
      let imageUrl = ''
      if (Array.isArray(res) && res.length > 0) {
        imageUrl = res[0].url
      } else if (res && res.url) {
        imageUrl = res.url
      } else if (typeof res === 'string') {
        imageUrl = res
      }
      
      if (imageUrl) {
        imageList.value.push(imageUrl)
        updateModelValue()
      } else {
        message.error('无法获取上传图片的URL')
      }
    } catch (error) {
      console.error('上传错误:', error)
      message.error('上传失败: ' + (error.message || '未知错误'))
    }
  }
}

// 处理图片加载错误
const handleImageError = (index) => {
  console.error('图片加载失败:', imageList.value[index])
  message.error('图片加载失败')
  imageList.value.splice(index, 1)
  updateModelValue()
}

// 处理图片移除
const handleRemove = (index) => {
  imageList.value.splice(index, 1)
  updateModelValue()
}

// 更新modelValue
const updateModelValue = () => {
  const value = imageList.value.join(';')
  emit('update:modelValue', value)
  emit('change', value)
}
</script>

<style lang="scss" scoped>
.image-upload {
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .image-item {
    position: relative;
    width: var(--upload-size);
    height: var(--upload-size);
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #eee;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .image-actions {
      position: absolute;
      top: 4px;
      right: 4px;
      display: none;
    }

    &:hover .image-actions {
      display: block;
    }
  }

  .upload-trigger {
    width: var(--upload-size);
    height: var(--upload-size);
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--primary-color);
      
      .n-icon, .upload-text {
        color: var(--primary-color);
      }
    }
    
    .upload-text {
      margin-top: 4px;
      font-size: 12px;
      color: #666;
    }
    
    .n-icon {
      color: #999;
    }
  }
}
</style> 